<template>
    <el-input 
        :placeholder="placeholder" 
        :maxlength="maxlength" 
        clearable 
        :value="searchWord" 
        @input="onInput" 
        class="input-with-search"
    >
        <el-button slot="append" @click="handleSearch">搜索</el-button >
    </el-input>
</template>
<script>
/**
 * @author wangzhixiang
 * @description 通用搜索框
 */
let TIMER = null;
let ms = +new Date();
export default {
    name: 'search',
    props: {
        // 是否开启实时搜索, 默认关闭
        liveSearch: {
            type: Boolean,
            default: false
        },
        // 搜索框占位字
        placeholder: {
            type: String,
            default: '请输入资源名称'
        },
        // 搜索框value值
        searchWord: {
            type: String,
            default: ''
        },
        // 字符串最大长度限制
        maxlength: {
            type: Number,
            default: 8
        }
    },
    methods: {
        onInput(value) {
            const newValue = value.replace(/\s+/g, '')
            this.$emit('update:searchWord', newValue)
            if (this.liveSearch) {
                clearTimeout(TIMER)
                TIMER = setTimeout(() => {
                    this.$emit('search', newValue)
                }, 600)
            }
        },
        handleSearch() {
            const newMs = +new Date()
            if (newMs - ms > 600) {
                this.$emit('search', this.searchWord)
                ms = newMs
            }
        }
    }
}
</script>
<style lang="scss" scoped>
    .input-with-search {
        width: 260px;
        float: right;
    }
</style>

<style lang="scss">
    @import '~@/styles/variables.scss';
    .input-with-search .el-input-group__append {
        background: $blue;
        border-color: $blue;
        color: #fff;
    }
</style>
